<?php

namespace App\Http\Imports\System;


use App\Models\MpcLocation;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class MpcLocationImport implements ToCollection
    {
    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
        {
        //编码1	规格2	代号3	花型4	上胶量(g)5	损耗率%6	门幅(米)7	备注8
        set_time_limit(0);
        $collection->filter(function ($v, $k)
            {
            if ($k == 0) {
                return;
                }
            $parent_name     = trim($v[0]);
            $name            = trim($v[1]);
            $department_name = trim($v[2]);
            $is_material     = trim($v[3]);
            $remark          = trim($v[4]);
            $parent_id       = 0;
            $department_id   = 0;

            if (!isEmpty($parent_name)) {
                $parent_data = MpcLocation::where("name", $parent_name)->first();
                if ($parent_data) {
                    $parent_id = $parent_data->id;
                    }
                else {
                    fail("第" . $k . "行父库位{$parent_name}不存在！导入失败");
                    }
                }

            if (isEmpty($name)) {
                fail("第" . $k . "行库位名称不能为空！导入失败");
                }
            else {
                $gdata = MpcLocation::where("name", $name)->first();
                if ($gdata) {
                    fail("第" . $k . "库位{$name}已存在！导入失败");
                    }
                }

            if (!isEmpty($department_name)) {
                $dept_data = MpcLocation::where("name", $parent_name)->first();
                if ($dept_data) {
                    $department_id = $dept_data->id;
                    }
                else {
                    fail("第" . $k . "部门不存在，导入失败！");
                    }
                }

            if (!in_array($is_material, ['是', '否'])) {
                fail("第" . $k . "是否原料库位必须填是/否！导入失败");
                }
            else {
                $is_material = $is_material == "是" ? 1 : 0;
                }

            MpcLocation::create([
                'name'          => $name,
                'parent_id'     => $parent_id,
                'department_id' => $department_id,
                'is_material'   => $is_material,
                'remark'        => $remark
            ]);
            });

        }
    }
